package weiyao.xinxidasai.controller;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import weiyao.xinxidasai.DTO.FileTreeNode;
import weiyao.xinxidasai.DTO.FolderDetailDTO;
import weiyao.xinxidasai.DTO.Result;
import weiyao.xinxidasai.Utils.ThreadLocal.UserHolder;
import weiyao.xinxidasai.pojo.FilesFolder;
import weiyao.xinxidasai.service.FolderService;

import java.util.List;

@RestController
@RequestMapping("/folders")
public class FolderController {
    @Autowired
    private FolderService folderService;


    @PostMapping("/createFolder")
    public Result createFolder(@RequestParam("path") String path) {
        try {
            return   folderService.createFolder(path);

        } catch (Exception e) {
            return Result.fail("创建失败: " + e.getMessage());
        }
    }


    @DeleteMapping("/deleteFolder")
    public Result deleteFolder(@RequestParam("folderId") Long folderId) {
        try {

            return folderService.deleteFolder(folderId);
        } catch (Exception e) {
            return Result.fail("删除失败: " + e.getMessage());
        }
    }

    @PutMapping("/updateFolderPath")
    public Result updateFolderPath(@RequestParam Long folderId,
                                   @RequestParam String newPath) {
        try {
            folderService.updateFolderPath(folderId, newPath);
            return Result.ok("文件夹路径更新成功");
        } catch (Exception e) {
            return Result.fail("更新失败: " + e.getMessage());
        }
    }

    @GetMapping("/getFolder")
    public Result searchFolderTrees(
            @RequestParam String path,
            @RequestParam(defaultValue = "false") boolean includeFiles) {

        try {
            Long userId = UserHolder.getUser().getUserId();
            List<FileTreeNode> trees = folderService.searchFolderTreesByKeyword(userId,path, includeFiles);
            return Result.ok(trees);
        } catch (Exception e) {
            return Result.fail("查询失败: " + e.getMessage());
        }
    }

    @GetMapping("/getUserFolders")
    public Result getFoldersByUser() {
        try {
            List<FilesFolder> folders = folderService.getFoldersByUser();
            return Result.ok(folders);
        } catch (Exception e) {
            return Result.fail("查询失败: " + e.getMessage());
        }
    }
}